﻿using System.IO;
using Pfz.Threading;

namespace Pfz.Remoting
{
	/// <summary>
	/// Represents a channel that uses MemoryMappedFiles for communication.
	/// </summary>
	public class MmfChannel:
		ThreadSafeDisposable,
		IChannel
	{
		private MmfChanneller _channeller;
		private MemoryMappedFileStream _stream;

		internal MmfChannel(MmfChanneller channeller, MemoryMappedFileStream stream)
		{
			_channeller = channeller;
			_stream = stream;

			channeller._channels.Add(this);
		}

		/// <summary>
		/// Releases all the resources used by this channel.
		/// </summary>
		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				var channeller = _channeller;
				if (channeller != null)
				{
					_channeller = null;

					var channels = channeller._channels;
					if (channels != null)
						lock(channels.DisposeLock)
							if (!channels.WasDisposed)
								channels.Remove(this);
				}

				Disposer.Dispose(ref _stream);
			}

			base.Dispose(disposing);
		}

		/// <summary>
		/// Gets the Channeller that controls this channel.
		/// </summary>
		public MmfChanneller Channeller
		{
			get
			{
				return _channeller;
			}
		}

		/// <summary>
		/// Gets the Stream of this channel.
		/// </summary>
		public Stream Stream
		{
			get
			{
				return _stream;
			}
		}

		IChanneller IChannel.Channeller
		{
			get
			{
				return _channeller;
			}
		}

		/// <summary>
		/// Gets the MemoryMappedFileName
		/// </summary>
		public string Name
		{
			get
			{
				return _stream.Name;
			}
		}

		string IChannel.LocalEndpoint
		{
			get
			{
				return Name;
			}
		}
		string IChannel.RemoteEndpoint
		{
			get
			{
				return Name;
			}
		}
	}
}
